import React, {
  useState,
  useCallback,
  FC,
  ReactNode,
  useEffect,
  useContext,
} from "react";
import { AnomalyContext } from "./AnomalyContext";
import { AnomalyItem } from "../components/MainBody/components/AnomalyContainer/components/AnomalyList";
import { BigScreenContext } from "@/pages/BigScreen/context/BigScreenContext";
import {
  fetchAnomalyOverviewAISummary,
  fetchEvaluationItems,
  updateEvaluationItem,
  fetchGroupTagMap,
} from "./services/anomaly";
import { message } from "@supcon/supcon-5t-design";
import { ANOMALY_NAME_TYPE_MAP, ANOMALY_TYPE_MAP, getAnomalyName, getAnomalyType } from "../constants";
import { getPosition } from "@/utils/position";

interface AnomalyEventProviderProps {
  children: ReactNode;
}

/**
 * 异常事件上下文提供者组件
 * 用于管理全局异常事件状态和处理函数
 */
const AnomalyEventProvider: FC<AnomalyEventProviderProps> = ({ children }) => {
  const token = localStorage.getItem("token");

  const [aiSummary, setAiSummary] = useState<string>("");
  const [aiSummaryLoading, setAiSummaryLoading] = useState<boolean>(false);
  // 异常事件状态
  const [alarmInfo, setAlarmInfo] = useState<any>([
    { type: "alarm", count: 0, details: 0 },
    { type: "warning", count: 0, details: 0 },
  ]);
  const [selectedAnomaly, setSelectedAnomaly] = useState<AnomalyItem | null>(
    null
  );
  // 新增分组标签映射状态
  const [groupTagMap, setGroupTagMap] = useState<Record<string, any>>({});
  const [groupTagMapLoading, setGroupTagMapLoading] = useState<boolean>(false);
  
  const context = useContext(BigScreenContext);
  // 将模拟数据放在Provider中
  const [anomalies, setAnomalies] = useState<AnomalyItem[]>([]);

  // 当前筛选状态，添加到上下文中，便于同步UI
  const [currentFilterValue, setCurrentFilterValue] = useState<string>("all");
  const [currentGroupValue, setCurrentGroupValue] = useState<string>("");
  const [currentSearchValue, setCurrentSearchValue] = useState<string>("");

  const getAnomalyValue = (json: string) => {
    try {
      console.log("json", json);
      let jsonData = JSON.parse(json);
      let realValue = jsonData.tag_value;
      return realValue;
    } catch (error) {
      console.error("获取异常值异常:", error);
      return "";
    }
  };

  const queryAnomalyOverviewAISummary = async () => {
    setAiSummaryLoading(true);
    try {
      const { status, content, msg } = await fetchAnomalyOverviewAISummary();
      if (status) {
        setAiSummary(content);
      } else {
        message.error(msg);
      }
    } catch (error) {
      console.error("获取异常概览AI摘要异常:", error);
      message.error("获取异常概览失败");
    } finally {
      setAiSummaryLoading(false);
    }
  };
  // 过滤后的异常数据
  const [filteredAnomalies, setFilteredAnomalies] = useState<AnomalyItem[]>([]);

  // 统计数据
  const [statistics, setStatistics] = useState({
    redAlerts: 0,
    yellowAlerts: 0,
    greenAlerts: 0,
  });

  // 过滤和搜索状态
  const [filterType, setFilterType] = useState("all");

  const [evaluationItemsLoading, setEvaluationItemsLoading] =
    useState<boolean>(false);
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const { chatRef } = useContext(BigScreenContext);

  // 获取分组标签映射
  const queryGroupTagMap = async () => {
    setGroupTagMapLoading(true);
    try {
      const { status, content, msg } = await fetchGroupTagMap();
      if (status) {
        setGroupTagMap(content || {});
      } else {
        message.error(msg);
      }
    } catch (error) {
      console.error("获取分组标签映射异常:", error);
      message.error("获取分组标签映射失败");
    } finally {
      setGroupTagMapLoading(false);
    }
  };

  // 异常事件处理函数
  const handleAnomalyClick = useCallback((anomaly: AnomalyItem) => {
    console.log("全局异常事件被触发:", anomaly);
    setSelectedAnomaly(anomaly);
    console.log(
      `请告诉我${anomaly.name}预警点的基本信息、历史趋势、异常原因和优化建议`
    );
    //chatRef?.current?.handleChat(`请告诉我${anomaly.name}预警点的基本信息、历史趋势、异常原因和优化建议`);
    // 这里可以添加其他全局处理逻辑
  }, []);

  const handleAnomalyIconClick = useCallback(
    (anomaly: AnomalyItem) => {
      console.log('handleAnomalyIconClick anomaly', anomaly);
      // 构建请求参数
      const params = {
        data: {
          id: Number(anomaly.evaluationItemId),
          isOpen: anomaly.isShelve ? 0 : 1,
          tagName: anomaly.code,
        },
        requestBase: {
          page: "1-10",
          sort: "-createTime",
        },
      };

      // 调用搁置接口
      updateEvaluationItem(params)
        .then(({ status, content, msg }) => {
          if (status) {
            // 直接更新前端状态，避免全量刷新
            const newAnomalies = anomalies.map((item) => {
              // ! 点的和 item 没法命中
              // if (item.id === anomaly.id) {
              const newAnomalTags = item.bottomTagResps.map((res) => {
                if (res.tagName === anomaly.code) {
                  return {
                    ...res,
                    isOpen: !res.isOpen,
                  };
                }
                return res;
              });
              return {
                ...item,
                bottomTagResps: newAnomalTags,
              };
              // }
              // return item;
            });
            console.log("newAnomalies", newAnomalies);
            setAnomalies(newAnomalies);
            setFilteredAnomalies(newAnomalies);

            // 如果当前选中的是被修改的异常，也需要更新选中状态
            if (selectedAnomaly && selectedAnomaly.id === anomaly.id) {
              setSelectedAnomaly({
                ...selectedAnomaly,
                isShelve: !selectedAnomaly.isShelve,
              });
            }
            // message.success(anomaly.isShelve ? "激活成功" : "搁置成功");
            message.success(!anomaly.isOpen ? "激活成功" : "搁置成功");
          } else {
            message.error(msg || "搁置失败");
          }
        })
        .catch((error) => {
          console.error("搁置异常:", error);
          message.error("搁置失败");
        });
    },
    [anomalies, selectedAnomaly]
  );

  // 过滤处理函数
  const handleFilter = useCallback(
    (type: string, groupType?: string, searchValue?:string) => {
      // 更新当前筛选状态
      setCurrentFilterValue(type);
      if (groupType !== undefined) {
        setCurrentGroupValue(groupType);
      }
      
      setFilterType(type);
      // 根据筛选类型构建查询参数
      let params: any = {
        data: {}
      };

      // 如果有状态筛选
      if (type !== "all") {
        // 将前端类型转换为接口需要的状态值
        const stateValue =
          type === "red"
            ? 30
            : type === "yellow"
              ? 20
              : type === "green"
                ? 10
                : null;
        if (stateValue) {
          params.data.state = String(stateValue);
        }
      }

      // 如果有分组筛选
      if (groupType) {
        params.data.groupType = groupType;
      }

      // 如果有搜索关键字，也加入参数
      if (searchValue?.trim?.()) {
        params.data.tagDesc = searchValue;
      }

      // 调用接口进行筛选
      queryEvaluationItems(params);
    },
    [currentSearchValue]
  );

  const handleInputChange = useCallback((keyword: string) => {
    setCurrentSearchValue(keyword);
  }, []);

  // 搜索处理函数
  const handleSearch = useCallback(
    (keyword: string) => {
      // 更新当前搜索关键字状态
      setCurrentSearchValue(keyword);
      // 构建搜索参数
      let params: any = {
        data: {}
      };

      if (keyword?.trim?.()) {
        params.data.tagDesc = keyword;
      }

      // 如果有筛选类型，也加入参数
      if (filterType !== "all") {
        const stateValue =
          filterType === "red"
            ? 30
            : filterType === "yellow"
              ? 20
              : filterType === "green"
                ? 10
                : null;
        if (stateValue) {
          params.data.state = String(stateValue);
        }
      }

      // 如果有分组类型，也加入参数
      if (currentGroupValue) {
        params.data.groupType = currentGroupValue;
      }

      // 调用接口进行搜索
      queryEvaluationItems(params);
    },
    [filterType, currentGroupValue]
  );

  // 初始化统计数据和过滤结果
  useEffect(() => {
    // 统计各类型数量
    const redCount = anomalies.filter((item) => item.type === "red").length;
    const yellowCount = anomalies.filter(
      (item) => item.type === "yellow"
    ).length;
    const greenCount = anomalies.filter((item) => item.type === "green").length;

    setStatistics({
      redAlerts: redCount,
      yellowAlerts: yellowCount,
      greenAlerts: greenCount,
    });
    console.log("anomalies", anomalies);
    // 设置过滤后的异常数据，这里使用全部数据，因为筛选已经在接口完成
    setFilteredAnomalies(anomalies);
    setSelectedAnomaly(anomalies?.[0]?.bottomTagResps?.[0] ? {
      ...anomalies?.[0]?.bottomTagResps?.[0],
      groupType: anomalies?.[0]?.groupType,
      evaluationItemId: anomalies?.[0]?.evaluationItemId,
      evaluationItemName: anomalies?.[0]?.name,
      name: anomalies?.[0]?.bottomTagResps?.[0]?.tagDesc,
      code: anomalies?.[0]?.bottomTagResps?.[0]?.tagName,
      location: ANOMALY_NAME_TYPE_MAP?.[Number(JSON.parse(anomalies?.[0]?.bottomTagResps?.[0]?.ext || "{}")?.status_now)] || "正常",
      type: ANOMALY_TYPE_MAP?.[Number(JSON.parse(anomalies?.[0]?.bottomTagResps?.[0]?.ext || "{}")?.status_now)] || "green",
      description: anomalies?.[0]?.bottomTagResps?.[0]?.tagDesc,
      position: getPosition(anomalies?.[0]?.bottomTagResps?.[0]?.tagDesc, anomalies?.[0]?.groupType),
      updateTime: anomalies?.[0]?.bottomTagResps?.[0]?.updateTime,
      predictTime: null,
      isShelve: anomalies?.[0]?.bottomTagResps?.[0]?.isOpen,
      value: Number(JSON.parse(anomalies?.[0]?.bottomTagResps?.[0]?.ext || "{}")?.tag_value),
    } : null);
  }, [anomalies]);

  // 获取评估项列表
  const queryEvaluationItems = async (params: any = {}) => {
    setEvaluationItemsLoading(true);
    try {
      const { status, content, msg } = await fetchEvaluationItems(params);
      if (status) {
        let finalResult: any = [];
        if (content.evaluationItems?.length > 0) {
          for (let i = 0; i < content.evaluationItems.length; i++) {
            let position = getPosition(content.evaluationItems[i].evaluationItemName);
            const convertedItem = {
              id: content.evaluationItems[i].id.toString(),
              type: getAnomalyType(
                content.evaluationItems[i].currentState
              ),
              groupType: content.evaluationItems[i].groupType,
              name: content.evaluationItems[i].evaluationItemName || "",
              code: content.evaluationItems[i].calTag || "",
              bottomTagResps: content.evaluationItems[i].bottomTagResps || [],
              location:
                getAnomalyName(
                  content.evaluationItems[i].currentState
                ) || "",
              description:
                content.evaluationItems[i].bottomTagResps?.find(
                (item: any) =>
                  item.evaluationId === content.evaluationItems[i].id
                )?.tagReason ||
                content.evaluationItems[i].abnormalCause ||
                "",
              updateTime: content.evaluationItems[i].updateTime || "",
              position,
              value:
                getAnomalyValue(
                  content.evaluationItems[i].bottomTagResps?.find(
                    (item: any) =>
                      item.evaluationId === content.evaluationItems[i].id
                  )?.ext
                ) || 0,
              isShelve: content.evaluationItems[i].isShelve,
              evaluationItemId: content.evaluationItems[i].id,
              isOpen: content.evaluationItems[i].isOpen,
            };
            finalResult.push(convertedItem);
          }
        }
        setAnomalies(finalResult || []);
        setAlarmInfo([
          {
            type: "alarm",
            count: content.alarm || 0,
            details: content.alarmSum || 0,
          },
          {
            type: "warning",
            count: content.warn || 0,
            details: content.warnSum || 0,
          },
        ]);
      } else {
        message.error(msg);
      }
    } catch (error) {
      console.error("获取评估项列表异常:", error);
      message.error("获取评估项列表失败");
    } finally {
      setEvaluationItemsLoading(false);
    }
  };

  const findItem = (name: string) => {
    // 先尝试匹配 evaluationItemName
    const itemByName = groupTagMap?.find?.((item: any) => item.evaluationItemName === name);
    if (itemByName) {
      return {
        evaluationItemName: itemByName.evaluationItemName,
        groupType: String(itemByName.groupType || '')
      };
    }

    // 如果没有匹配到 evaluationItemName，尝试匹配 tagDescList 中的项
    const itemByTagDesc = groupTagMap?.find?.((item: any) => 
      item.tagDescList?.some?.((tagDesc: string) => tagDesc === name)
    );
    
    if (itemByTagDesc) {
      return {
        evaluationItemName: itemByTagDesc.evaluationItemName,
        tagDesc: name,
        groupType: String(itemByTagDesc.groupType || '')
      };
    }

    // 如果都没匹配到，返回空对象
    return {};
  }

  // 组件首次加载时初始化异常列表和分组标签映射
  useEffect(() => {
    setFilteredAnomalies(anomalies);
    queryGroupTagMap();
  }, []);

  // 当 context.anomalyJson 变化时，重置筛选条件并重新获取数据
  useEffect(() => {
    if (token) {
      // 重置筛选状态
      const result = findItem(context.anomalyJson?.resource_list?.[0]?.id);
      setCurrentFilterValue("all");
      queryAnomalyOverviewAISummary();
      setCurrentGroupValue(result?.groupType ?? "");
      setCurrentSearchValue(result?.tagDesc ?? "")
      queryEvaluationItems({
        data: {
          ...result
        },
      });
    }
  }, [context.anomalyJson, token]);

  // 提供上下文值
  const contextValue = {
    selectedAnomaly,
    setSelectedAnomaly,
    handleAnomalyClick,
    anomalies,
    setAnomalies,
    filteredAnomalies,
    statistics,
    filterType,
    handleFilter,
    handleSearch,
    aiSummary,
    setAiSummary,
    aiSummaryLoading,
    fetchAISummary: fetchAnomalyOverviewAISummary,
    evaluationItemsLoading,
    handleInputChange,
    handleAnomalyIconClick,
    queryEvaluationItems,
    alarmInfo,
    setAlarmInfo,
    // 添加筛选状态到上下文
    currentFilterValue,
    currentGroupValue,
    currentSearchValue,
    // 添加分组标签映射到上下文
    groupTagMap,
    groupTagMapLoading,
    queryGroupTagMap,
  };

  return (
    <AnomalyContext.Provider value={contextValue}>
      {children}
    </AnomalyContext.Provider>
  );
};

export default AnomalyEventProvider;
